package info.xiao.dataStructrue.array;

/**
 * @Classname Rotate
 * @Description 轮转数组
 * @Href https://leetcode.cn/problems/rotate-array/
 * @Date 2023/3/14 9:58
 * @Created by 晓龙Oba
 */
public class Rotate {
    public static void main(String[] args) {
        int[] nums = {-1};
        int step = 2;
        retate(nums, step);
        System.out.println(nums);
    }

    private static int[] retate(int[] nums, int step) {
        step = step % nums.length;
        // 通过数组翻转的方式进行数组轮转
        nums = reversArr(nums, 0, nums.length - 1);
        nums = reversArr(nums, 0, step - 1);
        nums = reversArr(nums, step, nums.length - 1);
        return nums;
    }


    private static int[] reversArr(int[] nums, int start, int end) {
        while (start < end) {
            nums[start] += nums[end];
            nums[end] = nums[start] - nums[end];
            nums[start++] -= nums[end--];
        }
        return nums;

    }

    /**
     * 思路是对的 超时了
     */
    private static int[] retate1(int[] nums, int step) {
        while (step-- > 0) {
            int temp = nums[0];
            for (int i = 0; i < nums.length; i++) {
                int index = i + 1 <= nums.length - 1 ? i + 1 : 0;
                nums[index] += temp;
                temp = nums[index] - temp;
                nums[index] -= temp;
            }
        }
        return nums;
    }

}
